/**
 *
 */
package com.zhengtoon.mctoon.conv.service.sdzc;

import com.qitoon.framework.core.exception.BusinessException;
import com.zhengtoon.mctoon.conv.bean.ConvAttachment;
import com.zhengtoon.mctoon.conv.bean.sdzc.Letter;
import com.zhengtoon.mctoon.conv.bean.sdzc.LetterAttachment;
import com.zhengtoon.mctoon.conv.bean.sdzc.Reply;
import com.zhengtoon.mctoon.conv.bean.sdzc.TransferLetter;
import com.zhengtoon.mctoon.conv.dao.sdzc.LetterAttachmentMapper;
import com.zhengtoon.mctoon.conv.dao.sdzc.LetterMapper;
import com.zhengtoon.mctoon.conv.dao.sdzc.ReplyMapper;
import com.zhengtoon.mctoon.conv.dao.sdzc.TransferLetterMapper;
import com.zhengtoon.mctoon.conv.dto.param.ConvLetterParam;
import com.zhengtoon.mctoon.conv.dto.param.LetterInputParam;
import com.zhengtoon.mctoon.conv.dto.param.UploadOutputResult;
import com.zhengtoon.mctoon.conv.dto.sdzc.*;
import com.zhengtoon.mctoon.conv.exception.ConvPhotoExceptionCode;
import com.zhengtoon.mctoon.conv.service.sdzc.LetterService;
import com.zhengtoon.mctoon.conv.service.sdzc.ZfhfSystemService;
import com.zhengtoon.mctoon.conv.utils.*;
import com.zhengtoon.mctoon.conv.utils.sdzc.ZfhfConstant;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 信件 impl实现
 *
 * @author 刘振华
 * @since 2017-04-12
 * Copyright: Copyright (c) 2017
 * Company:北京政务通科技有限公司
 */
@Service
public class LetterServiceImpl implements LetterService {

    private static Logger log = LoggerFactory.getLogger(LetterServiceImpl.class);

    private final static String COMMUNITY_CODE = SysConfig.getPropertyValue("config.communityCode");
    private final static String COMMUNITY_UUID = SysConfig.getPropertyValue("config.communityUUID");

    private final static String WRITER_CONFIG = SysConfig.getPropertyValue("sdzc.default_writer");
    private final static String WRITER_NAME_CONFIG = SysConfig.getPropertyValue("sdzc.default_writer_name");
    private final static String EMAIL_CONFIG = SysConfig.getPropertyValue("sdzc.default_email");


    @Autowired
    private LetterMapper letterMapper;

    @Autowired
    private LetterAttachmentMapper letterAttachmentMapper;

    @Autowired
    private ZfhfSystemService zfhfService;  // 中科软系统服务


    @Override
    public boolean addLetterFromConvphoto(ConvLetterParam convLetterParam) {

        try {
            // 参数校验
            if (StringUtils.isAnyBlank(convLetterParam.getLetterTitle(), convLetterParam.getLetterContent(), convLetterParam.getUserId())
                    || convLetterParam.getConvId() == null
                    || convLetterParam.getLetterAttachList() == null) {
                throw new BusinessException(ConvPhotoExceptionCode.CONV_ADD_LETTER_PARAM_IS_NULL);
            }
            // 设置或生成更多属性
            Letter letter = new Letter();
            letter.setLetterType(ZfhfConstant.ZFHF_CONV_LETTER_TYPE_DEFALUT); // 随手拍默认政风投诉
            letter.setOpenType(ZfhfConstant.ZFHF_CONV_LETTER_OPEN_TYPE_NOT);       // 随手拍默认不公开
            letter.setLetterTitle(convLetterParam.getLetterTitle());
            letter.setLetterContent(convLetterParam.getLetterContent());
            letter.setUserId(convLetterParam.getUserId());
            letter.setConvId(convLetterParam.getConvId());

            generateMoreField(letter);

            String base64Stream = getBase64StreamFromCloud(convLetterParam.getLetterAttachList());
            letter.setLetterAttachZipStream(base64Stream);

            // 调用中科软系统提交信件
            boolean isSubmitSuccess = zfhfService.submitCommunityLetter(letter, true);

            if (!isSubmitSuccess) {
                return false;
            }
            log.info("提交政风行风系统信件成功, 标题:{},内部信件id:{}",letter.getLetterTitle(),letter.getSysLetterId()) ;
            // 本地存储信件表
            Integer row = letterMapper.addLetter(letter);

            // 存储附件表
            batchInsertAttachment(letter.getSysLetterId(), convLetterParam.getLetterAttachList());

            return row.equals(1);
        } catch (Exception e) {
            log.error("提交首都之窗信件失败", e);
            throw new BusinessException(ConvPhotoExceptionCode.SUBMIT_LETTER_FAIL);
        }

    }

    /**
     * 获取base64字符串  144637
     *
     * @param letterAttachList
     * @return
     */
    private String getBase64StreamFromCloud(List<ConvAttachment> letterAttachList) {
        String[] urlList = new String[letterAttachList.size()];
        int index = 0;
        for (ConvAttachment item : letterAttachList) {
            urlList[index] = item.getFileUrl();
            index++;
        }
        File[] files = CloudAppUtils.downloadPublicUrls(urlList);

        String zipFiles2B64 = ZipUtils.zipFiles2B64(files);

        for (File file : files) {
            file.delete();
        }

        return zipFiles2B64;
    }

    /**
     * 批量插入附件表  144637
     *
     * @param sysLetterId
     * @param urlList
     */
    private void batchInsertAttachment(String sysLetterId, List<ConvAttachment> urlList) {
        List<LetterAttachment> attachList = new ArrayList<>();

        if (CollectionUtils.isEmpty(urlList)) {
            return;
        }
        for (ConvAttachment item : urlList) {
            LetterAttachment letterAttach = new LetterAttachment();
            letterAttach.setSysLetterId(sysLetterId);
            letterAttach.setLetterAttachmentUrl(item.getFileUrl());
            long currentTime = new Date().getTime();
            letterAttach.setCreateTime(currentTime);
            letterAttach.setUpdateTime(currentTime);
            attachList.add(letterAttach);
        }

        letterAttachmentMapper.batchInsert(attachList);
    }

    /**
     * 处理或生成默认字段    144637
     *
     * @return
     */
    private void generateMoreField(Letter letter) {

        // 1. 判断用户是否通过实名认证
        // 2. 查询用户实名名片姓名

        String writer = "";
        String writerName = "";
        String email = "";

        // TODO 随手拍的信件默认writer,writerName,邮箱  @张子成

        writer = StringUtils.isBlank(WRITER_CONFIG) ?
                ZfhfConstant.ZFHF_DEFAULT_NO_CERT_WRITER : WRITER_CONFIG;
        writerName = StringUtils.isBlank(WRITER_NAME_CONFIG) ?
                ZfhfConstant.ZFHF_DEFAULT_NO_CERT_WRITER_NAME : WRITER_NAME_CONFIG;
        email = StringUtils.isBlank(EMAIL_CONFIG) ?
                ZfhfConstant.ZFHF_DEFAULT_NO_CERT_EMAIL : EMAIL_CONFIG;

        letter.setWriter(writer);
        letter.setWriterName(writerName);
        letter.setWriterEmail(email);

        letter.setCommunityCode(COMMUNITY_CODE);
        letter.setCommunityUuid(COMMUNITY_UUID);

        String sysLetterId = generateBjtSysLetterId();
        letter.setSysLetterId(sysLetterId);

        letter.setRemindType(ZfhfConstant.ZFHF_REMIND_TYPE);

        letter.setWriterMobile("");
        letter.setWriterTelephone("");
        letter.setWriterPostCode("");
        letter.setWriterAddress("");

        long currentTime = new Date().getTime();
        letter.setCreateTime(currentTime);
        letter.setUpdateTime(currentTime);

        // 设置状态为未回复
        letter.setBjtStatus(AppConstant.BJT_SYS_LETTER_STATUS_SUBMIT);
    }

    /**
     * 生成内部信件id     144637
     *
     * @return String
     * @author 144637
     */
    private String generateBjtSysLetterId() {
        // TODO 生成内部信件id 规则 暂时使用时间戳
        return AppConstant.BJT_SYS_LETTER_ID_PREFIX + new Date().getTime();
    }
}